import request from './request'
import type { ApiResponse } from './request'

export interface Product {
  id?: number
  name: string
  price: number
  cid: number
}

// 添加时间戳参数防止缓存
const getNoCacheParam = () => {
  return { t: new Date().getTime() }
}

export const getProducts = (): Promise<ApiResponse<Product[]>> => {
  return request<Product[]>({
    url: '/product/All',
    method: 'get',
    params: getNoCacheParam(), // 添加时间戳防止缓存
  })
}

export const getProductById = (id: number): Promise<ApiResponse<Product>> => {
  return request<Product>({
    url: `/product/${id}`,
    method: 'get',
    params: getNoCacheParam(), // 添加时间戳防止缓存
  })
}

export const addProduct = (data: Product): Promise<ApiResponse<Product>> => {
  return request<Product>({
    url: '/product/add',
    method: 'post',
    data,
    params: getNoCacheParam(), // 添加时间戳防止缓存
  })
}

export const updateProduct = (data: Product): Promise<ApiResponse<Product>> => {
  return request<Product>({
    url: '/product/update',
    method: 'put',
    data,
    params: getNoCacheParam(), // 添加时间戳防止缓存
  })
}

export const deleteProduct = (id: number): Promise<ApiResponse<void>> => {
  return request<void>({
    url: `/product/delete/${id}`,
    method: 'delete',
    params: getNoCacheParam(), // 添加时间戳防止缓存
  })
}

// 刷新产品缓存
export const refreshProductCache = (): Promise<ApiResponse<void>> => {
  return request<void>({
    url: '/product/refreshCache',
    method: 'post',
    params: getNoCacheParam(), // 添加时间戳防止缓存
  })
}
